import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'
import { paginate } from '~/helper/paginate'
import { Pagination } from '~/helper/paginate/pagination'
import { GoodDto, GoodQueryDto, GoodUpdateDto } from '~/modules/goods/good.dto'
import { GoodEntity } from '~/modules/goods/good.entity'

@Injectable()
export class GoodsService {
  constructor(@InjectRepository(GoodEntity) private goodRepository: Repository<GoodEntity>) {
  }

  async create(dto: GoodDto): Promise<void> {
    await this.goodRepository.save(dto)
  }

  findAll() {
    return `This action returns all goods`
  }

  findOne(id: number) {
    return `This action returns a #${id} good`
  }

  async update(id: number, dto: GoodUpdateDto): Promise<void> {
    await this.goodRepository.update(id, dto)
  }

  remove(id: number) {
    return `This action removes a #${id} good`
  }

  async list({
    page,
                   pageSize,
                   name,
                   price,
                   color,
                   size,
  }: GoodQueryDto): Promise<Pagination<GoodEntity>> {
    const queryBuilder = this.goodRepository.createQueryBuilder('good').where({
      ...(name ? { name: Like(`%${name}%`) } : null),
      ...(price ? { price } : null),
      ...(color ? { color: Like(`%${color}%`) } : null),
      ...(size ? { size: Like(`%${size}%`) } : null),
    })
    return paginate(queryBuilder, { page, pageSize })
  }

  async info(id: number): Promise<GoodEntity> {
    const good = await this.goodRepository.createQueryBuilder('good').where({ id }).getOne()
    if (!good) {
      throw new NotFoundException('Good Not Found')
    }
    return good
  }

  async delete(good: GoodEntity): Promise<void> {
    if (!good) {
      throw new BadRequestException('good is Empty')
    }
    await this.goodRepository.delete(good.id)
  }
}
